﻿@page "/order-query"
@using Microsoft.EntityFrameworkCore
@using Microsoft.AspNetCore.Components.QuickGrid
@using BlazorAppAuth.Models
@using BlazorAppAuth.Data
@using Microsoft.Office.Interop.Excel
@inject IDbContextFactory<BlazorAppAuth.Data.BlazorAppAuthContext> DbFactory
@implements IAsyncDisposable
@rendermode InteractiveServer

<AuthorizeView>
	<Authorized>
		<h3>订单查询</h3>

		<form class="row g-3 my-4">
			<div class="row">
				<label for="FilterType" class="col-auto col-form-label">查询模式</label>
				<div class="col-auto">
					<InputSelect id="FilterType" @bind-Value="FilterType" class="form-select">

						<option value="用户">用户</option>
						<option value="时间段">时间段</option>
					</InputSelect>
				</div>
				<div class="col-auto">
					<button type="button" class="btn btn-primary" @onclick="ExportExcel">导出Excel</button>
				</div>
			</div>
		</form>

		@if (FilterType == "用户")
		{
			<div class="row g-3 align-items-center">
				<div class="col-auto">
					<label for="inputPassword6" class="col-form-label">用户名</label>
				</div>
				<div class="col-auto">
					<input id="queryUser" class="form-control" @bind="queryUserName">
				</div>
				<div class="col-auto">
					<button type="button" class="btn btn-primary" @onclick="DoQuery">查询</button>
				</div>
			</div>
		}
		@if (FilterType == "时间段")
		{
			<div class="row align-items-center">
				<div class="col-auto">
					<label for="" class="col-form-label">起始时间:</label>
				</div>
				<div class="col-auto">
					<input type="datetime-local" @bind="queryStartAt" />
				</div>
				<div class="col-auto">
					<label for="" class="col-form-label">结束时间:</label>
				</div>
				<div class="col-auto">
					<input type="datetime-local" @bind="queryEndAt" />
				</div>
				<div class="col-auto">
					<button type="button" class="btn btn-primary" @onclick="DoQuery">查询</button>
				</div>
			</div>

		}



		<QuickGrid Items="FilterableOrder" Class="table" @ref="myGrid">
			<PropertyColumn Property="@(o => o.Id)" Title="ID" />
			<PropertyColumn Property="@(o => o.OrderId)" Title="订单编号" />
			<PropertyColumn Property="@(o => o.OrderType)" Title="订单类型" />
			<PropertyColumn Property="@(o => o.UserType)" Title="用户类型" />
			<PropertyColumn Property="@(o => o.UserName)" Title="用户名" />
			<PropertyColumn Property="@(o => o.StartTime)" Title="启动时间" />
			<PropertyColumn Property="@(o => o.OrderTime)" Title="下单时间" />
			<PropertyColumn Property="@(o => o.Quantity)" Title="数量" />
			<PropertyColumn Property="@(o => o.Priority)" Title="优先级" />
			<PropertyColumn Property="@(o => o.AssemblyTime)" Title="装配时间" />
			<PropertyColumn Property="@(o => o.DrillingTime)" Title="钻孔时间" />
			<PropertyColumn Property="@(o => o.AssemblyCount)" Title="装配次数" />
			<PropertyColumn Property="@(o => o.DrillingCount)" Title="钻孔次数" />
			<PropertyColumn Property="@(o => o.OrderStatus)" Title="订单状态" />
			<PropertyColumn Property="@(o => o.ElectricityConsumption)" Title="订单用电量（w·h）" />
			<PropertyColumn Property="@(o => o.GasConsumption)" Title="订单用气量（L）" />
		</QuickGrid>
	</Authorized>
</AuthorizeView>

@code {
	BlazorAppAuthContext context = default!;

	[CascadingParameter]
	private Task<AuthenticationState> authenticationStateTask { get; set; }


	private string FilterType { get; set; } = "用户";
	string queryUserName;
	DateTime queryStartAt, queryEndAt;

	private QuickGrid<Models.Order> myGrid;

	private IQueryable<Models.Order> FilterableOrder = default!;


	async Task ExportExcel()
	{

		Application excel = new Application();
		Workbook workbook = excel.Workbooks.Add();
		Worksheet worksheet = workbook.ActiveSheet;
		worksheet.Cells[1, 1] = "ID";
		worksheet.Cells[1, 2] = "订单编号";
		worksheet.Cells[1, 3] = "订单类型";
		worksheet.Cells[1, 4] = "用户类型";
		worksheet.Cells[1, 5] = "用户名";
		worksheet.Cells[1, 6] = "启动时间";
		worksheet.Cells[1, 7] = "下单时间";
		worksheet.Cells[1, 8] = "数量";
		worksheet.Cells[1, 9] = "优先级";
		worksheet.Cells[1, 10] = "装配时间";
		worksheet.Cells[1, 11] = "钻孔时间";
		worksheet.Cells[1, 12] = "装配次数";
		worksheet.Cells[1, 13] = "钻孔次数";
		worksheet.Cells[1, 14] = "订单状态";
		worksheet.Cells[1, 15] = "订单用电量（w·h）";
		worksheet.Cells[1, 16] = "订单用气量（L）";

		var orders = await FilterableOrder.ToListAsync();
		for (int i = 0; i < orders.Count; i++)
		{
			var order = orders[i];
			worksheet.Cells[i + 2, 1] = order.Id;
			worksheet.Cells[i + 2, 2] = order.OrderId;
			worksheet.Cells[i + 2, 3] = order.OrderType;
			worksheet.Cells[i + 2, 4] = order.UserType;
			worksheet.Cells[i + 2, 5] = order.UserName;
			worksheet.Cells[i + 2, 6] = order.StartTime.ToString();
			worksheet.Cells[i + 2, 7] = order.OrderTime.ToString();
			worksheet.Cells[i + 2, 8] = order.Quantity;
			worksheet.Cells[i + 2, 9] = order.Priority;
			worksheet.Cells[i + 2, 10] = order.AssemblyTime.ToString();
			worksheet.Cells[i + 2, 11] = order.DrillingTime.ToString();
			worksheet.Cells[i + 2, 12] = order.AssemblyCount;
			worksheet.Cells[i + 2, 13] = order.DrillingCount;
			worksheet.Cells[i + 2, 14] = order.OrderStatus;
			worksheet.Cells[i + 2, 15] = order.ElectricityConsumption;
			worksheet.Cells[i + 2, 16] = order.GasConsumption;
		}
		// 保存到磁盘
		string tempFilePath = Path.Combine(Path.GetTempPath(), "Orders.xlsx");
		workbook.SaveAs(tempFilePath, XlFileFormat.xlWorkbookDefault);
		workbook.Close();
		excel.Quit();

		// 读取文件并转换为 Base64
		var content = await File.ReadAllBytesAsync(tempFilePath);
		var base64 = Convert.ToBase64String(content);
		var fileName = "Orders.xlsx";

		// 触发浏览器下载
		await js.InvokeVoidAsync("downloadFile", fileName, base64);

		// 删除临时文件
		File.Delete(tempFilePath);

	}


	private async Task DoQuery()
	{
		if (FilterType == "用户")
		{
			FilterableOrder = context.Order.Where(o => o.UserName.Contains(queryUserName));

		}
		else if (FilterType == "时间段")
		{
			FilterableOrder = context.Order.Where(o => o.OrderTime >= queryStartAt && o.OrderTime <= queryEndAt);
		}


		await myGrid.RefreshDataAsync();
	}

	public async Task CheckLogin()
	{
		var authState = await authenticationStateTask;
		var user = authState.User;

		if (!user.Identity.IsAuthenticated)
		{
			NavigationManager.NavigateTo("/login");
		}

	}

	protected async override void OnInitialized()
	{
		await CheckLogin();
		context = DbFactory.CreateDbContext();
		FilterableOrder = context.Order;
		queryStartAt = DateTime.Now.AddHours(-2);
		queryEndAt = DateTime.Now;
	}



	public async ValueTask DisposeAsync() => await context.DisposeAsync();
}
